console.log("🔥 IRCTC FINAL AUTOMATION");


// ======================
// 🖱️ REAL USER CLICK
// ======================
function realClick(el) {

  if (!el) return;

  let rect = el.getBoundingClientRect();

  let x = rect.left + rect.width / 2;
  let y = rect.top + rect.height / 2;

  ["mousedown", "mouseup", "click"].forEach(type => {
    el.dispatchEvent(new MouseEvent(type, {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: x,
      clientY: y
    }));
  });
}

// ======================
// HELPER
// ======================
function setVal(el, val) {
  if (!el || !val) return;

  const setter = Object.getOwnPropertyDescriptor(
    HTMLInputElement.prototype,
    "value"
  ).set;

  setter.call(el, val);

  el.dispatchEvent(new Event("input", { bubbles: true }));
  el.dispatchEvent(new Event("change", { bubbles: true }));
}

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

// ======================
// 🔐 LOGIN AUTO FILL
// ======================
setInterval(() => {

  let user = document.querySelector("input[formcontrolname='userid']");
  let pass = document.querySelector("input[type='password']");

  if (user && pass && user.offsetParent !== null) {

    chrome.storage.local.get(null, (data) => {
      setVal(user, data.irctc_credentials?.user_name);
      setVal(pass, data.irctc_credentials?.password);
      console.log("🔐 LOGIN FILLED");
    });

  }

}, 500);

// ======================
// 🚆 MAIN FLOW
// ======================
(async () => {

  await sleep(1500);

  // 🔥 WAIT LOGIN COMPLETE
for (let i = 0; i < 20; i++) {

  let loginBox = document.querySelector("input[formcontrolname='userid']");

  if (!loginBox) {
    console.log("✅ Login Done");
    break;
  }

  console.log("⏳ Waiting Login...");
  await sleep(500);
}

  chrome.storage.local.get(null, async (data) => {

    let inputs = document.querySelectorAll("input[aria-autocomplete='list']");
    if (inputs.length >= 2) {
      setVal(inputs[0], data.journey_details?.from);
      await sleep(100);
      setVal(inputs[1], data.journey_details?.to);
    }

    await sleep(300);

    let dateInput = document.querySelectorAll("input[type='text']")[2];

if (dateInput) {

  dateInput.click();
  await sleep(300);

  let [day, month, year] = data.journey_details?.date.split("/");

  day = parseInt(day);
  month = parseInt(month) - 1;
  year = parseInt(year);

  let tries = 0;

  while (tries < 12) {

    let title = document.querySelector(".ui-datepicker-title");

    if (!title) break;

    let text = title.innerText.trim(); // e.g. May 2026
    let current = new Date(text);

    let currentMonth = current.getMonth();
    let currentYear = current.getFullYear();

    if (currentMonth === month && currentYear === year) {

      // 🎯 select date
      document.querySelectorAll(".ui-datepicker-calendar td a").forEach(d => {
        if (parseInt(d.innerText) === day) {
          d.click();
        }
      });

      break;

    } else {

      let nextBtn = document.querySelector(".ui-datepicker-next");

      if (nextBtn) {
        nextBtn.click();
        await sleep(300);
      } else {
        break;
      }

    }

    tries++;
  }
}

    await sleep(400);

    let dropdown = document.querySelector(".ui-dropdown");

    if (dropdown) {
      dropdown.click();
      await sleep(200);

      document.querySelectorAll("li.ui-dropdown-item").forEach(item => {
        if (item.innerText.includes("(" + data.journey_details?.class + ")")) {
          item.click();
        }
      });
    }

    await sleep(400);

   // ======================
// 🎯 AUTO SELECT QUOTA (FIXED)
// ======================
// ======================
// 🎯 AUTO SELECT QUOTA (FINAL FIX)
// ======================
async function selectQuotaIRCTC(quotaText = "TATKAL") {

  let dropdowns = document.querySelectorAll(".ui-dropdown");

  let quotaDropdown = null;

  // 🔥 ONLY find dropdown which contains quota label
  dropdowns.forEach(d => {

    let label = d.querySelector(".ui-dropdown-label");

    if (!label) return;

    let text = label.innerText.toUpperCase();

    // 👉 quota dropdown always has these values
    if (
      text === "GENERAL" ||
      text === "TATKAL" ||
      text === "PREMIUM TATKAL"
    ) {
      quotaDropdown = d;
    }

  });

  if (!quotaDropdown) {
    console.log("❌ Quota dropdown not found");
    return;
  }

  // 🔥 open dropdown
  quotaDropdown.click();
  await sleep(200);

  // 🔥 visible panel
  let panel = [...document.querySelectorAll(".ui-dropdown-panel")]
    .find(p => p.offsetParent !== null);

  if (!panel) {
    console.log("❌ Panel not found");
    return;
  }

  let items = panel.querySelectorAll("li.ui-dropdown-item");

  // 🔥 exact match only
  for (let item of items) {

    let txt = item.innerText
      .replace(/\s+/g, " ")
      .trim()
      .toUpperCase();

    if (txt === quotaText.toUpperCase()) {
      item.click();
      console.log("✅ FINAL SELECT:", txt);
      return;
    }
  }

  console.log("❌ Not found:", quotaText);
}


// 🔥 CALL ADDED HERE
   let quota = data.journey_details?.quota || "GN";

let map = {
  GN: "GENERAL",
  TQ: "TATKAL",
  PT: "PREMIUM TATKAL"
};

await selectQuotaIRCTC(map[quota]);
    await sleep(200);

    


 // 🔥 STRONG SEARCH CLICK (RETRY)
for (let i = 0; i < 15; i++) {

  let btn = Array.from(document.querySelectorAll("button"))
    .find(b => b.innerText.toLowerCase().includes("search"));

  if (btn && !btn.disabled && btn.offsetParent !== null) {

    realClick(btn);
    console.log("🚀 Search Click SUCCESS");
    break;
  }

  await sleep(500);
}
   

// ======================
// ⏳ WAIT FOR TRAIN LOAD (NEW)
// ======================
async function waitForTrainList() {

  for (let i = 0; i < 30; i++) {

    let trains = document.querySelectorAll("app-train-avl-enq, div[class*='train']");

    if (trains.length > 0) {
      console.log("✅ Train List Loaded");
      return trains;
    }

    await sleep(150);
  }

  console.log("❌ Train List Not Loaded");
  return [];
}

// ======================
// 🚆 TRAIN SELECT FINAL
// ======================

// 🔥 extract number
let fullTrain = data.journey_details?.train_no || "";
let trainNo = fullTrain.split("-")[0].trim();

// 🔥 wait for trains
let trains = await waitForTrainList();

for (let train of trains) {

  let match = train.innerText.match(/\((\d{5})\)/);

  if (match && match[1] === trainNo) {

    console.log("🚆 TRAIN FOUND CORRECT");

    // ======================
    // 🔄 REFRESH
    // ======================
    let refreshBtn = Array.from(train.querySelectorAll("*"))
      .find(el => el.innerText && el.innerText.toLowerCase().includes("refresh"));

    if (refreshBtn) {
      realClick(refreshBtn);
      console.log("🔄 Refresh Clicked");
      await sleep(1000);
    }

    // ======================
// 🎯 FINAL CLASS SELECT FIX
// ======================
let targetClass = data.journey_details?.class;
let classSelected = false;

for (let i = 0; i < 5; i++) { // 🔁 retry

  let tabs = train.querySelectorAll("span, strong");

  for (let tab of tabs) {

    let txt = tab.innerText?.toUpperCase();

    if (txt && txt.includes(targetClass)) {

      tab.scrollIntoView({ block: "center" });

      await sleep(100);

      realClick(tab);
      await sleep(200);
      realClick(tab);

      console.log("🎯 Class Selected:", targetClass);

      classSelected = true;
      break;
    }
  }

  if (classSelected) break;

  await sleep(100);
}
await sleep(1000);





 await sleep(100);
        train.scrollIntoView({ behavior: "smooth", block: "center" });

        let wl = train.querySelector(".pre-avl");

        if (wl) {
          wl.click();
          await sleep(500);
        }


    // ======================
    // 🚀 BOOK NOW (STABLE)
    // ======================
    async function clickBookNow(train) {

      for (let i = 0; i < 10; i++) {

        let bookBtn = Array.from(train.querySelectorAll("button"))
          .find(btn => btn.innerText && btn.innerText.toLowerCase().includes("book"));

        if (bookBtn && bookBtn.offsetParent !== null) {

          bookBtn.scrollIntoView({ block: "center" });

          await sleep(200);

          realClick(bookBtn);

          console.log("🚀 BOOK CLICK SUCCESS");

          return true;
        }

        await sleep(300);
      }

      console.log("❌ Book Button Not Found");
      return false;
    }

    await clickBookNow(train);

    break;
  }

}
  });

})();

// ======================
// 👤 PASSENGER FILL FINAL
// ======================
async function fillPassengerDetails() {

  console.log("👤 Passenger Start");

  await sleep(200);

  chrome.storage.local.get(null, async (data) => {

    let passengers = data.journey_details?.passengers;
    let mobile = data.journey_details?.mobile;

    if (!passengers || passengers.length === 0) return;

    function getNames() {
      return Array.from(document.querySelectorAll("input[placeholder='Name']"))
        .filter(el => el.offsetParent !== null);
    }

    let names = getNames();

    let addBtn = [...document.querySelectorAll("button, a")]
      .find(el => el.innerText.includes("Add Passenger"));

    // ➕ ADD ROW
    while (names.length < passengers.length) {

      addBtn?.click();

      let prev = names.length;

      for (let i = 0; i < 10; i++) {
        await sleep(500);
        let updated = getNames();
        if (updated.length > prev) {
          names = updated;
          break;
        }
      }

      names = getNames();
    }

    let ages = Array.from(document.querySelectorAll("input[placeholder='Age']"))
      .filter(el => el.offsetParent !== null);

    let genders = Array.from(
      document.querySelectorAll("select[formcontrolname='passengerGender']")
    ).filter(el => el.offsetParent !== null);

    for (let i = 0; i < passengers.length; i++) {

      let p = passengers[i];

      if (names[i]) setVal(names[i], p.name);

      await sleep(100);

      if (ages[i]) setVal(ages[i], p.age);

      await sleep(100);

      if (genders[i]) {
        genders[i].value = p.gender;
        genders[i].dispatchEvent(new Event("change", { bubbles: true }));
      }

      await sleep(200);
    }

    // ======================
    // 📱 MOBILE AUTO FILL (ADDED)
    // ======================
    let mobileInput = document.querySelector(
      "input[formcontrolname='mobileNumber'], input[placeholder*='Mobile']"
    );

    if (mobileInput && mobile) {
      setVal(mobileInput, mobile);
      console.log("📱 Mobile Filled");
    }


    // ======================
// 🔥 FINAL STRONG FIX
// ======================
// ======================
setTimeout(() => {

  console.log("💳 Payment Start");

  window.scrollTo(0, document.body.scrollHeight);

// ======================
// ✅ CONFIRM BERTH FINAL (DIRECT INPUT FIX)
// ======================
let confirmInput = document.querySelector("#confirmberths");

if (confirmInput && !confirmInput.checked) {
  confirmInput.click();
  console.log("✅ Confirm Berth Clicked FINAL");
}
  // ======================
  // 💳 UPI SELECT (FINAL FIX)
  // ======================
  let upiRow = Array.from(document.querySelectorAll("tr"))
    .find(tr => tr.innerText.toLowerCase().includes("bhim/upi"));

  if (upiRow) {

    let upiBox = upiRow.querySelector(".ui-radiobutton-box");

    if (upiBox && !upiBox.classList.contains("ui-state-active")) {
      upiBox.click();
      console.log("✅ UPI Selected");
    }
  }

  // ======================
  // 🚀 CONTINUE CLICK
  // ======================
  setTimeout(() => {

    let btn = Array.from(document.querySelectorAll("button"))
      .find(b => b.innerText.toLowerCase().includes("continue"));

    if (btn) {
      btn.click();
      console.log("🚀 Continue Clicked");
    }

  }, 300);

}, 2000);

    console.log("✅ PASSENGERS FILLED");

  });
}

// ======================
// RUN
// ======================
let done = false;

let interval = setInterval(() => {

  if (done) return;

  let nameBox = document.querySelector("input[placeholder='Name']");

  if (nameBox && nameBox.offsetParent !== null) {
    done = true;
    clearInterval(interval);
    fillPassengerDetails();
  }

}, 3000);





// ======================
// ⚡ CAPTCHA FAST MODE (MULTI TRY FIX)
// ======================
function handleCaptchaFast() {

  console.log("⚡ Captcha Multi Mode");

  let inputInterval = setInterval(() => {

    let input = document.querySelector("#captcha");

    if (input && input.offsetParent !== null) {

      console.log("✅ Captcha Ready");

      // 🔥 focus always
      input.focus();

      // 🔥 prevent multiple listener
      if (!input.dataset.listenerAdded) {

        input.dataset.listenerAdded = "true";

        input.addEventListener("input", () => {

          // 🔥 every time user types
          if (input.value.length >= 4) {

            console.log("⌨️ Typing Done");

            setTimeout(() => {

              let btn = Array.from(document.querySelectorAll("button"))
                .find(b => b.innerText.toLowerCase().includes("continue"));

              if (btn) {
                btn.click();
                console.log("🚀 Continue Clicked");
              }

            }, 300);
          }

        });
      }

    }

  }, 200);
}

setTimeout(() => {
  handleCaptchaFast();
}, 13000);







// ======================
// 💳 FINAL PAY CLICK (FIXED)
// ======================
function handleFinalPaymentClick() {

  console.log("💳 Waiting Pay Button...");

  let donePay = false;

  let payInterval = setInterval(() => {

    if (donePay) return;

    let btn = document.querySelector("button.btn.btn-primary");

    if (btn && btn.innerText.includes("Pay") && btn.offsetParent !== null) {

      donePay = true;
      clearInterval(payInterval);

      console.log("✅ Pay Button Found");

      setTimeout(() => {

        realClick(btn);

        console.log("🚀 Pay Click Done");

      }, 800);

    }

  }, 1000);
}


setTimeout(() => {
  handleFinalPaymentClick();
}, 15000);



// ======================
// 📱 AUTO QR CLICK (FINAL WORKING)
// ======================
function handleQrAutoClick() {

  console.log("📱 Searching QR Button...");

  let doneQR = false;

  let qrInterval = setInterval(() => {

    if (doneQR) return;

    // 🔥 EXACT ELEMENT
    let qrBtn = document.querySelector("span[onclick='submitUpiQrForm()']");

    if (qrBtn && qrBtn.offsetParent !== null) {

      doneQR = true;
      clearInterval(qrInterval);

      console.log("✅ QR Element Found");

      setTimeout(() => {

        realClick(qrBtn); // 🔥 CLICK ELEMENT

        console.log("📱 QR Clicked FINAL");

      }, 1500);
    }

  }, 1000);
}



setTimeout(() => {
  handleQrAutoClick();
}, 4000);




// ======================
// 🎉 SUCCESS POPUP OVERLAY FINAL (REAL DATA)
// ======================

// 🔥 REAL DATA EXTRACT
function getIRCTCData() {

  let text = document.body.innerText;

  let pnrMatch = text.match(/PNR\s*[:\-]?\s*(\d{10})/i);
  let pnr = pnrMatch ? pnrMatch[1] : "---";

  let fareMatch = text.match(/₹\s*([\d,]+\.\d+)/);
  let fare = fareMatch ? fareMatch[1] : "---";

  let paymentMatch = text.match(/Payment\s*Mode\s*[:\-]?\s*(.*)/i);
  let payment = paymentMatch ? paymentMatch[1].split("\n")[0] : "---";

  let trainMatch = text.match(/Train\s*[:\-]?\s*(.*)/i);
  let train = trainMatch ? trainMatch[1].split("\n")[0] : "---";

  return { pnr, fare, payment, train };
}


// 🔥 OVERLAY UI
function showSuccessOverlay(data) {

  let overlay = document.createElement("div");

  overlay.innerHTML = `
  <div style="
    position:fixed;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:360px;
    background:#2e8b57;
    color:#fff;
    font-family:Arial;
    border-radius:15px;
    overflow:hidden;
    z-index:999999;
    box-shadow:0 0 25px rgba(0,0,0,0.6);
  ">
    
    <div style="background:#0b5fa5;padding:15px;text-align:center;font-size:20px;font-weight:bold;">
      🌊 Success By Tatkal Safer 🌊
    </div>

    <div style="padding:20px;text-align:center;line-height:2;">
      <div>FARE: ${data.fare}</div>
      <div>PNR: ${data.pnr}</div>
      <div>BOOKING TIME: ${new Date().toLocaleTimeString()}</div>
      <div>PAYMENT: ${data.payment}</div>
      <div>TRAIN: ${data.train}</div>
    </div>

  </div>
  `;

  document.body.appendChild(overlay);

  // 🔥 auto hide (optional)
  setTimeout(() => {
    overlay.remove();
  }, 15000);
}


// 🔥 SUCCESS DETECT
function detectSuccessPage() {

  let interval = setInterval(() => {

    let text = document.body.innerText.toLowerCase();

    if (
  text.includes("transaction successful") ||
  text.includes("booking confirmed") ||
  (text.includes("pnr") && text.includes("passenger"))
) {

      clearInterval(interval);

      console.log("🎉 SUCCESS PAGE DETECTED");

      let data = getIRCTCData();

      console.log("📊 REAL DATA:", data);

      showSuccessOverlay(data);
    }

  }, 1000);
}


// 🔥 RUN
setTimeout(() => {
  detectSuccessPage();
}, 5000);


